import {listAllClassesUsingGet} from '@/services/student-management-system/banjimokuai';
import {
  addTeachClassCourseUsingPost,
  updateTeachClassCourseUsingPost,
} from '@/services/student-management-system/jiaoshibanjishoukejiekou';
import { listAllCourseUsingGet } from '@/services/student-management-system/kechengmokuai';
import {getAllUsersUsingPost} from '@/services/student-management-system/yonghumokuai';
import {Form, message, Select} from 'antd';
import {forwardRef, useEffect, useImperativeHandle, useState} from 'react';

interface UpdateTeacherCourseProps {
  isEdit: boolean;
  editTeacherCourse?: API.TeacherCourseVO;
  onCloseModal?: () => void;
}

export interface UpdateTeacherCourseMethods {
  submitForm: () => Promise<boolean>;
}

export const UpdateTeacherCourse = forwardRef<UpdateTeacherCourseMethods, UpdateTeacherCourseProps>(
  (props, ref) => {
    const {isEdit, editTeacherCourse, onCloseModal} = props;
    const [form] = Form.useForm();

    // 存储下拉数据
    interface optionsType {
      value: number | undefined;
      label: string | undefined;
    }

    const [classOptions, setClassOptions] = useState<optionsType[]>([]);
    const [courseOptions, setCourseOptions] = useState<optionsType[]>([]);
    const [teacherOptions, setTeacherOptions] = useState<optionsType[]>([]);

    // 加载状态
    // const [loading, setLoading] = useState(true);

    const submitForm = async () => {
      // 获取表单提交数据
      const values = await form.validateFields();
      console.log(values);
      const res = isEdit
        ? await updateTeachClassCourseUsingPost({...values})
        : await addTeachClassCourseUsingPost({...values});
      if (res.code === 200) {
        message.success('操作成功');
        onCloseModal?.();
        return true;
      } else {
        message.error('操作失败：' + res.msg);
        return false;
      }
    };

    useEffect(() => {
      const fetchData = async () => {
        const [classRes, courseRes, teacherRes] = await Promise.all([
          listAllClassesUsingGet(),
          listAllCourseUsingGet(),
          getAllUsersUsingPost({ current: 1, role: 1 }),
        ]);

        // 处理班级数据
        const classOptions =
          classRes.data?.map((item) => ({
            value: item.id,
            label: item.className,
          })) ?? [];
        // 处理课程数据
        const courseOptions =
          courseRes.data?.map((item) => ({
            value: item.id,
            label: item.courseName,
          })) ?? [];

        // 处理教师数据
        const teacherOptions =
          teacherRes.data?.records?.map((item) => ({
            value: item.id,
            label: item.realName,
          })) ?? [];

        setClassOptions(classOptions);
        setCourseOptions(courseOptions);
        setTeacherOptions(teacherOptions);
      };

      if (editTeacherCourse) {
        form.setFieldsValue({
          className: editTeacherCourse.className,
          teacherName: editTeacherCourse.teacherName,
          courseName: editTeacherCourse.courseName,
          classId: editTeacherCourse.classId,
          teacherId: editTeacherCourse.teacherId,
          courseId: editTeacherCourse.courseId,
        });

      }
      fetchData();
    }, [editTeacherCourse, form]);

    useImperativeHandle(ref, () => ({submitForm}));

    return (
      <Form form={form} labelCol={{span: 8}} wrapperCol={{span: 16}} autoComplete="off">
        <Form.Item label="班级" name="classId" rules={[{required: true}]}>
          <Select placeholder="选择班级" optionFilterProp="label" options={classOptions}/>
        </Form.Item>

        <Form.Item label="课程" name="courseId" rules={[{required: true}]}>
          <Select placeholder="选择课程" optionFilterProp="label" options={courseOptions}/>
        </Form.Item>

        <Form.Item label="授课老师" name="teacherId" rules={[{required: true}]}>
          <Select placeholder="选择授课老师" optionFilterProp="label" options={teacherOptions}/>
        </Form.Item>
      </Form>
    );
  },
);
